import { NextRequest, NextResponse } from 'next/server'

// 直接登录API路由作为备选方案
export async function POST(request: NextRequest) {
  console.log('[Direct Login API] 收到登录请求')

  try {
    // 读取请求体
    const body = await request.json()
    const { username, password } = body

    console.log('[Direct Login API] 登录验证:', { username, password: '***' })

    // 首先尝试连接真实后端
    try {
      console.log('[Direct Login API] 尝试连接后端...')
      
      const backendResponse = await fetch('http://localhost:8232/admin/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ username, password })
      })

      console.log('[Direct Login API] 后端响应状态:', backendResponse.status)

      if (backendResponse.ok) {
        const data = await backendResponse.json()
        console.log('[Direct Login API] 后端登录成功')
        return NextResponse.json(data)
      } else {
        console.log('[Direct Login API] 后端返回错误，使用模拟登录')
        throw new Error('Backend not available')
      }
    } catch (backendError) {
      console.log('[Direct Login API] 后端连接失败，使用模拟登录:', backendError)
      
      // 模拟登录逻辑
      if (username === 'admin' && password === 'admin123') {
        const successResponse = {
          success: true,
          token: 'mock-jwt-token-' + Date.now(),
          user: {
            id: 1,
            username: 'admin',
            email: 'admin@entrepreneur-home.com',
            nickname: '超级管理员',
            role: 'admin'
          }
        }
        console.log('[Direct Login API] 模拟登录成功:', successResponse)
        return NextResponse.json(successResponse)
      } else {
        const errorResponse = {
          success: false,
          message: '用户名或密码错误'
        }
        console.log('[Direct Login API] 模拟登录失败:', errorResponse)
        return NextResponse.json(errorResponse, { status: 401 })
      }
    }
  } catch (error) {
    console.error('[Direct Login API] 登录处理错误:', error)
    return NextResponse.json(
      { 
        success: false,
        error: '登录处理失败', 
        message: error instanceof Error ? error.message : '未知错误'
      },
      { status: 500 }
    )
  }
}

// 处理OPTIONS请求（CORS预检）
export async function OPTIONS() {
  console.log('[Direct Login API] 处理OPTIONS请求')
  return new NextResponse(null, {
    status: 200,
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type, Authorization',
      'Access-Control-Max-Age': '86400',
    },
  })
}